package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.TCheckgroupMapper;
import com.itheima.entity.GroupItem;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = CheckGroupService.class)
public class CheckGroupServiceImpl implements CheckGroupService {

    @Autowired
    private TCheckgroupMapper checkGroupDao;
    @Override
    @Transactional
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        checkGroupDao.add(checkGroup);
        if (checkitemIds != null && checkitemIds.length>0 ){
            List<GroupItem> list = Collections.emptyList();
            for (Integer in: checkitemIds) {
                new GroupItem(checkGroup.getId(),in);
            }
            checkGroupDao.setGroupItem(list);
        }
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<CheckGroup> page = checkGroupDao.selectByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public CheckGroup findById(Integer id) {
        return checkGroupDao.findById(id);
    }

    @Override
    public List<Integer> findCheckItemIdsByCheckGroupId(Integer id) {
        return checkGroupDao.findCheckItemIdsByCheckGroupId(id);
    }

    @Override
    @Transactional
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        checkGroupDao.edit(checkGroup);
        checkGroupDao.deleteByGroupId(checkGroup.getId());
        if (checkitemIds != null && checkitemIds.length>0 ){
            List<GroupItem> list = new ArrayList<>();
            for (Integer in: checkitemIds) {
                GroupItem item = new GroupItem(checkGroup.getId(), in);
                list.add(item);
            }
            checkGroupDao.setGroupItem(list);
        }
    }

    @Override
    public List<CheckGroup> findAll() {
        return checkGroupDao.findAll();
    }

    @Override
    public void delete(Integer id) {
        checkGroupDao.deleteByGroupId(id);
        checkGroupDao.deleteById(id);
    }
}
